﻿using System;
using System.Windows.Forms;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YArchitech.Controls;

namespace YArchitech.Plumbing
{
	[Transaction(TransactionMode.Manual)]
	public class ViewHold : IExternalCommand
	{
		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			Selection selection = commandData.Application.ActiveUIDocument.Selection;
			Document document = commandData.Application.ActiveUIDocument.Document;
			Autodesk.Revit.DB.View activeView = document.ActiveView;
			Transaction transaction = null;
			Result result;
			try
			{
				transaction = new Transaction(document, "视角锁定");
				transaction.Start();
				if (!(activeView is View3D))
				{
					YJKMessageBox.Information("当前活动视图非3D视图，请选择3D视图！");
					transaction.Commit();
					result = Autodesk.Revit.UI.Result.Failed;
				}
				else
				{
					View3D view3D = activeView as Autodesk.Revit.DB.View3D;
					if (view3D.Name.Contains("{") || view3D.Name.Contains("}"))
					{
						YJKMessageBox.Information("视图名字中含有'{'或'}'非法符号，此操作不可用！\n请选择其他视图或者更改视图名称后，再操作！");
						transaction.Commit();
						result = Autodesk.Revit.UI.Result.Failed;
					}
					else
					{
						if (view3D.IsLocked)
						{
							if (YJKMessageBox.Show("该视图已经锁定，是否解锁？\n解锁后，所有标注信息会丢失！！", MessageBoxButtons.OKCancel) == DialogResult.OK)
							{
								view3D.Unlock();
							}
						}
						else
						{
							view3D.SaveOrientationAndLock();
							YJKMessageBox.Information("视图视角已锁定！");
						}
						transaction.Commit();
						result = Autodesk.Revit.UI.Result.Succeeded;
					}
				}
			}
			catch (Exception ex)
			{
				YJKMessageBox.Show(ex.Message);
				transaction.Commit();
				result = Autodesk.Revit.UI.Result.Failed;
			}
			return result;
		}
	}
}
